package com.tomato.gateway.predicate;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义 Predicate
 *
 * @author lizhifu
 * @date 2022/3/12
 */
@Component
@Slf4j
public class HeaderUserNoRoutePredicateFactory extends AbstractRoutePredicateFactory<HeaderUserConfig> {
    public static final String USER_NO = "UserNo";

    public HeaderUserNoRoutePredicateFactory() {
        super(HeaderUserConfig.class);
    }
    @Override
    public ShortcutType shortcutType() {
        return ShortcutType.GATHER_LIST;
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userNo");
    }
    @Override
    public Predicate<ServerWebExchange> apply(HeaderUserConfig config) {
        List<String> userNos = config.getUserNo();
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                // head 信息  predicates:    - HeaderUserNo=123456
                String userNo = serverWebExchange.getRequest().getHeaders().getFirst(USER_NO);
                log.info("自定义 Predicate 获取 userNo is {}",userNo);
                if (!StringUtils.isEmpty(userNo)) {
                    return userNos.contains(userNo);
                }
                return false;
            }
            @Override
            public String toString() {
                return String.format("Header: userNo=%s", config.getUserNo());
            }
        };
    }
}
